import axios from 'axios'
import { Notification, MessageBox } from 'element-ui'
import router from '@/router'

// 创建axios实例
const service = axios.create({
    baseURL: '/api',
    timeout: 5000
})
// 请求拦截
service.interceptors.request.use(async config => {
    if (localStorage.getItem('token')) {
        config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
    }
    let {
        is: isDel = false,
        content = '此操作将永久删除该文件, 是否继续?',
        title = '提示'
    } = config.warning || {}
    if (config.method == 'delete' || isDel) {
        await MessageBox.confirm(content, title, { type: 'warning' })
    }
    return config
})
// 响应拦截
service.interceptors.response.use(res => {
    if (res.data.code == 1) {
        Notification.error({
            title: res.data.message
        })
        return Promise.reject('error')
    } else if (res.data.code == 401) {
        Notification.error({
            title: 'token无效'
        })
        localStorage.clear()
        router.push('/login')
        return Promise.reject('token无效')
    } else {
        return res.data
    }

})

export default service